<template>
  <div class="wrapper">
    <div class="actions" style="margin-bottom: 10px">
      <div class="left">
        <el-button type="primary" plain size="mini" @click="handleClickExport"
          >导出</el-button
        >
        <!-- <el-tag v-if="tableKey == 1" style="
                height: 27px;
                line-height: 27px;
                margin-left:10px;
                border-color: #92d6ff;
                background-color: #e6f7ff;
                ">
                    <span style="font-weight: bold;
                color: black;">共内容</span>
                </el-tag> -->
      </div>
    </div>
    <div style="width: 100%" v-if="tableData.length > 0" :key="indexListdata">
      <el-table
        :default-sort="sortRule"
        ref="table"
        @sort-change="sortChange"
        v-loading="loading"
        :data="tableData"
        border
        :height="HeightList"
        style="width: 100%"
      >
        <el-table-column
          prop=""
          label="序号"
          width="50"
          type="index"
        ></el-table-column>
        <el-table-column
          sortable="custom"
          :width="item.weight"
          v-for="(item, index) in headerData"
          :key="index"
          :prop="item.show_name"
          :label="item.title"
          :align="item.align"
        >
        </el-table-column>
        <el-table-column prop=""> </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { AnalysisCustomer, AnalysisCustomerLoss } from "@/api/report";
import { commonAdd } from "@/utils/mUtils";

export default {
  name: "reportTable",
  components: {},
  props: ["searchParams", "tableKey", "currentParam"],
  data() {
    return {
      loading: false,
      tableData: [],
      headerData: [],
      oldData: [],
      sortRule: {
        prop: null,
        order: null,
      },
      indexListdata: "",
    };
  },
  watch: {},
  mounted() {
    this.getCharts(this.currentParam);
    if (this.tableKey == 1) {
      this.HeightList = document.documentElement.clientHeight - 300;
    } else if (this.tableKey == 2) {
      this.HeightList = document.documentElement.clientHeight - 250;
    }

    // // console.log("宽度", document.documentElement.clientWidth);
    // // console.log("高度", document.documentElement.clientHeight);
  },
  methods: {
    initList(paramList) {
      this.indexListdata = this.tableData.length + Math.random();
      // console.log(this.indexListdata, "")
      this.getCharts(paramList);
    },
    getCharts(params) {
      if (this.tableKey == 1) {
        AnalysisCustomer({
          ...params,
        }).then((res1) => {
          if ((res1 || {}).code === 10000) {
            this.tableData = res1.data.data;
            this.headerData = res1.data.item_list;
            this.indexListdata = this.tableData.length + Math.random();
            // console.log(this.indexListdata, "")
            this.loading = false;
          } else {
            this.tableData = [];
            this.headerData = [];
            this.indexListdata = this.tableData.length + Math.random();
            // console.log(this.indexListdata, "")
            this.loading = false;
          }
          // this.afterCrudRefresh();
        });
      } else if (this.tableKey == 2) {
        AnalysisCustomerLoss({
          ...params,
        }).then((res1) => {
          if ((res1 || {}).code === 10000) {
            this.tableData = res1.data.data;
            this.headerData = res1.data.item_list;
            this.loading = false;
          } else {
            this.tableData = [];
            this.headerData = [];
            this.loading = false;
          }
          // this.afterCrudRefresh();
        });
      }
    },

    handleClickExport() {
      this.$emit("export", this.tableKey);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        const values = data.map((item) => item[column.property]);
        let sum = 0;
        // console.log(values);
        const isNumber = values.every(
          (item) => (item && this.isNumber(item)) || item == ""
        );
        const isEmpty = values.every((item) => item == undefined || item == "");

        const isPercent = values.every(
          (item) => (item && item.indexOf("%") > 0) || item == ""
        );
        values.forEach(function (item, index) {
          if (item == null) {
            item = 0;
          }
          if (typeof item == "string" && item.indexOf("%") > 0) {
            item = Number(item.split("%")[0]);
          }
          // var aaa = Number(item);
          if (!isNaN(aaa)) {
            sum = commonAdd(sum, Number(item));
          } else {
            sum = null;
          }
        });
        // console.log(sum);
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (isEmpty) {
          sums[index] = "";
          return;
        }
        if (isNumber) {
          if (isPercent) {
            sums[index] = sum + "%";
            return;
          } else {
            sums[index] = sum;
            return;
          }
        } else {
          sums[index] = "";
          return;
        }
      });

      return sums;
    },
    afterCrudRefresh() {
      // 不能直接用=号赋值，避免this.oldData 与 this.tableData 指向同一个地址
      if (this.tableData.length > 0) {
        this.oldData.length = 0;
        this.tableData.forEach((item) => {
          this.oldData.push(item);
        });
      }
      // 点击下一页或者翻页后清除排序
      if (this.$refs.table) this.$refs.table.clearSort();
    },
    // 自定义排序
    sortChange(column) {
      const prop = column.prop;
      if (prop) {
        this.proptype = prop;
        const isNumber = this.tableData.every((item) => {
          return (
            this.isNumber(item[this.proptype]) || item[this.proptype] == ""
          );
        });
        // console.log(isNumber, 'isNumber==========------==============');

        if (column.order === "ascending") {
          const first = this.tableData.shift();
          this.tableData = this.tableData.sort((a, b) =>
            this.ascSortFun(a, b, isNumber)
          );
          this.tableData.unshift(first);
        } else if (column.order === "descending") {
          const first = this.tableData.shift();
          this.tableData = this.tableData.sort((a, b) =>
            this.desSortFun(a, b, isNumber)
          );
          this.tableData.unshift(first);
        } else {
          // 再点击向上【向下】恢复原始排序
          this.tableData.length = 0;
          this.oldData.forEach((item) => {
            this.tableData.push(item);
          });
        }
      }
    },
    // 升序排列方法
    ascSortFun(a, b, isNumber) {
      if (!isNumber) {
        const aLength = a[this.proptype] === null ? 0 : a[this.proptype].length;
        const bLength = b[this.proptype] === null ? 0 : b[this.proptype].length;
        // console.log('not number', aLength - bLength);
        return aLength - bLength;
      } else {
        // console.log(parseFloat(a[this.proptype] || 0), parseFloat(b[this.proptype] || '0'), parseFloat(a[this.proptype] || '0') - parseFloat(b[this.proptype] || '0'));
        return (
          parseFloat(a[this.proptype] || "-1") -
          parseFloat(b[this.proptype] || "-1")
        );
      }
    },
    // 降序排列方法
    desSortFun(a, b, isNumber) {
      if (!isNumber) {
        const bLength = b[this.proptype] === null ? 0 : b[this.proptype].length;
        const aLength = a[this.proptype] === null ? 0 : a[this.proptype].length;
        // console.log('not number', bLength - aLength);

        return bLength - aLength;
      } else {
        // console.log(parseFloat(b[this.proptype] || 0), parseFloat(a[this.proptype] || 0), parseFloat(b[this.proptype] || 0) - parseFloat(a[this.proptype] || 0));

        return (
          parseFloat(b[this.proptype] || -1) -
          parseFloat(a[this.proptype] || -1)
        );
      }
    },
    // 校验只要是数字（包含正负整数，0以及正负浮点数）就返回true
    isNumber(val) {
      var regPos = /^\d+(\.\d+)?$/; // 非负浮点数
      var regNeg =
        /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
      var regPercent = new RegExp(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/);
      if (regPos.test(val) || regNeg.test(val) || regPercent.test(val)) {
        // console.log('1111111111');
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  .actions {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: 100%;
    background-color: #fff;

    .el-button + .el-dropdown,
    .el-dropdown + .el-button {
      margin-left: 10px;
    }
  }

  /deep/ .el-table__body-wrapper {
    order: 1;
  }
}
</style>